import {
  BarsOutlined,
  CarOutlined,
  CheckCircleOutlined,
  ContainerOutlined,
  FieldTimeOutlined,
  LoadingOutlined,
  PayCircleOutlined,
  PictureOutlined,
  ReconciliationOutlined,
  SmileOutlined,
} from '@ant-design/icons';
import { ModalForm, ProCard } from '@ant-design/pro-components';
import { Image, message, Steps, Tooltip } from 'antd';
import { useEffect, useState } from 'react';
import { getParkingOrder } from '../service';
import styles from './style.less';
import type { ParkingOrderDetail } from '../types.d';
import EnhancedTag from './components/EnhancedTag';
import ChargeRule from './components/ChargeRule';
import { diffTimes, handleInOutType, numFormat, timeRender } from '@/utils/utils';
import EnhancedTip from './components/EnhancedTip';
import PaymentRecord from './components/PaymentRecord';
import ChangePlate from './components/ChangePlate';
import ChangeLogList from './components/ChangeLogList';
import { useModel } from 'umi';
import { Auths } from '@/utils/types.d';
import CancelOrder from '../components/CancelOrder';
import ChangeTime from './components/ChangeTime';
import ChangeTimeList from './components/ChangeTimeList';
type TStatus = 'error' | 'process' | 'finish' | 'wait';
const getStepStatus = (order?: ParkingOrderDetail): { out: TStatus; end: TStatus } => {
  if (order?.isEnded) return { out: 'finish', end: 'finish' };
  if (order?.carOut) return { out: 'process', end: 'wait' };
  return { out: 'wait', end: 'wait' };
};
const { Step } = Steps;

const handleLongText = (str: string = '') => {
  return str.slice(0, 20) + (str.length > 20 ? '...' : '');
};

const getCanRefundAmount = (num1 = 0, num2 = 0) => Math.max(num1 - num2, 0);

export default (props: { orderNo: string; visible: boolean; close: () => void }) => {
  const { initialState } = useModel('@@initialState');
  const { orderNo, visible, close } = props;
  const [currOrder, setCurrOrder] = useState<ParkingOrderDetail>();
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.parkingOrder || []) : new Set();
  const ifModify = auths.has(Auths.MODIFY);
  const refreshDetail = () => {
    getParkingOrder(orderNo).then((res) => {
      if (res?.success) {
        setCurrOrder(res.data);
        return;
      } else {
        setCurrOrder(undefined);
        message.error({ key: 'order_detail', content: res?.message || '获取失败' });
        return;
      }
    });
  };
  useEffect(() => {
    if (orderNo && orderNo.length > 0) {
      getParkingOrder(orderNo).then((res) => {
        if (res?.success) {
          setCurrOrder(res.data);
          return;
        } else {
          message.error({ key: 'order_detail', content: res?.message || '获取失败' });
          return;
        }
      });
    }
  }, [orderNo]);
  return (
    <ModalForm
      width="85vw"
      style={{
        minWidth: '1000px',
      }}
      submitter={false}
      className={styles.detail}
      visible={visible}
      modalProps={{ destroyOnClose: true, maskClosable: false, onCancel: close }}
    >
      <ProCard
        gutter={1}
        title={
          <div>
            <ContainerOutlined
              style={{
                color: '#888',
              }}
            />
            <span style={{ margin: '0 12px 0 8px' }}>
              订单编号：{currOrder?.orderNo || orderNo}
            </span>
            <EnhancedTag
              payStatus={currOrder?.payStatus}
              status={currOrder?.status}
              isEnded={currOrder?.isEnded}
              carOut={currOrder?.carOut}
              canceled={currOrder?.canceled}
            />
          </div>
        }
      >
        <ProCard
          colSpan={6}
          title="停车路段"
          layout="center"
          bodyStyle={{
            padding: 0,
            position: 'relative',
          }}
          style={{
            backgroundColor: '#eee',
            height: '130px',
          }}
        >
          <span className={styles.cardtext}>
            <Tooltip title={currOrder?.parkingLotName || ''}>
              {handleLongText(currOrder?.parkingLotName) || ''}
            </Tooltip>
          </span>
        </ProCard>
        <ProCard
          colSpan={4}
          title="泊位编号"
          layout="center"
          bodyStyle={{
            padding: 0,
            position: 'relative',
          }}
          style={{
            backgroundColor: '#eee',
            height: '130px',
          }}
        >
          <span className={styles.cardtext}>{currOrder?.spotId || '暂无数据'}</span>
          <span className={styles.sensorInfo}>地磁编号: {currOrder?.sensorSn || '暂无数据'}</span>
        </ProCard>
        <ProCard
          colSpan={4}
          layout="center"
          bodyStyle={{
            padding: 0,
          }}
          title={
            <>
              车牌号码
              {currOrder && !currOrder.canceled && ifModify && (
                <ChangePlate
                  reload={() => {
                    refreshDetail();
                  }}
                  orderNo={currOrder.orderNo}
                  plateNumber={currOrder.plateNumber || ''}
                  plateColor={currOrder.plateColor}
                  vehicleType={currOrder.vehicleType}
                />
              )}
            </>
          }
          style={{
            backgroundColor: '#eee',
            height: '130px',
          }}
        >
          <span className={styles.cardtext}>{currOrder?.plateNumber || '暂无数据'}</span>
          {/* <EditOutlined twoToneColor="#5895d0" /> */}
        </ProCard>
        <ProCard
          colSpan={4}
          layout="center"
          title={
            <>
              停车时长
              {currOrder &&
                !currOrder.isEnded &&
                !currOrder.canceled &&
                currOrder.carOut &&
                ifModify && (
                  <ChangeTime
                    currOrder={currOrder}
                    reload={() => {
                      refreshDetail();
                    }}
                  />
                )}
            </>
          }
          bodyStyle={{
            padding: 0,
          }}
          style={{
            backgroundColor: '#eee',
            height: '130px',
          }}
        >
          <span className={styles.cardtext}>
            {diffTimes(currOrder?.outTime || new Date(), currOrder?.inTime)}
          </span>
        </ProCard>
        <ProCard
          colSpan={3}
          layout="center"
          title="应付金额(元)"
          bodyStyle={{
            padding: 0,
          }}
          style={{
            backgroundColor: '#eee',
            height: '130px',
          }}
        >
          <span className={styles.cardtext}>
            {numFormat((currOrder?.payableAmount || 0) / 100)}
          </span>
        </ProCard>
        <ProCard
          colSpan={3}
          layout="center"
          title="实付金额(元)"
          bodyStyle={{
            padding: 0,
          }}
          style={{
            backgroundColor: '#eee',
            height: '130px',
          }}
        >
          <span className={styles.cardtext}>{numFormat((currOrder?.actualAmount || 0) / 100)}</span>
        </ProCard>
      </ProCard>
      {currOrder?.isMember && (
        <span
          style={{
            paddingLeft: '28px',
            color: '#999',
          }}
        >
          * 会员卡车辆，免去费用
        </span>
      )}
      <ProCard ghost>
        {currOrder && !currOrder?.isMember && (
          <ProCard
            colSpan={12}
            bodyStyle={{
              paddingTop: '5px',
              paddingBottom: '5px',
            }}
            title={
              <>
                <BarsOutlined
                  style={{
                    color: '#888',
                  }}
                />
                <span style={{ margin: '0 12px 0 8px' }}>收费规则</span>
              </>
            }
          >
            {/* <RulesDetail chargeRule={currOrder.chargeRule} flag /> */}
            {/* <ChargeRule chargeRule={currOrder.chargeRule} carType={currOrder.vehicleType} /> */}
            {currOrder.isImport ? (
              <div>导入订单，无对应收费规则</div>
            ) : (
              <ChargeRule chargeRule={currOrder.chargeRule} carType={currOrder.vehicleType} />
            )}
          </ProCard>
        )}
        <ProCard
          title={
            <>
              <PictureOutlined
                style={{
                  color: '#888',
                }}
              />
              <span style={{ margin: '0 12px 0 8px' }}>停车图片</span>
            </>
          }
          bodyStyle={{
            paddingTop: '5px',
            paddingBottom: '5px',
          }}
        >
          {currOrder && currOrder?.imageArr?.length > 0 ? (
            <Image.PreviewGroup>
              {currOrder?.imageArr?.map((item) => (
                <Image width={180} height={200} src={item} key={item} />
              ))}
            </Image.PreviewGroup>
          ) : (
            '暂无图片'
          )}
        </ProCard>
      </ProCard>

      <ProCard
        title={
          <>
            <FieldTimeOutlined
              style={{
                color: '#888',
              }}
            />
            <span style={{ margin: '0 12px 0 8px' }}>交易过程</span>
          </>
        }
        bodyStyle={{
          paddingTop: '5px',
          paddingBottom: '5px',
        }}
      >
        <div>
          <Steps style={{ paddingTop: '50px', width: '100%' }} labelPlacement="vertical">
            <Step
              status="finish"
              title="车辆驶入"
              icon={<EnhancedTip icon={<CarOutlined />} text={timeRender(currOrder?.inTime)} />}
              description={handleInOutType(currOrder?.inType)}
            />
            <Step
              status="finish"
              title={currOrder?.ticketPrintTime ? '打印小票' : '订单生成'}
              icon={
                <EnhancedTip
                  icon={<ContainerOutlined />}
                  text={timeRender(currOrder?.ticketPrintTime || currOrder?.createTime)}
                />
              }
              description={currOrder?.ticketPrintTime ? '人工打印' : '系统生成'}
            />
            {!currOrder?.carOut && (
              <Step
                status={'process'}
                title="停车中"
                icon={<EnhancedTip icon={<LoadingOutlined />} text={timeRender(Date.now())} />}
              />
            )}
            <Step
              status={getStepStatus(currOrder).out}
              title="车辆驶出"
              icon={
                <EnhancedTip icon={<CheckCircleOutlined />} text={timeRender(currOrder?.outTime)} />
              }
              description={currOrder?.carOut && handleInOutType(currOrder?.outType)}
            />
            <Step
              status={getStepStatus(currOrder).end}
              title="订单结束"
              icon={
                <EnhancedTip
                  icon={<SmileOutlined />}
                  text={timeRender(currOrder?.orderEndedTime)}
                />
              }
              description={
                currOrder?.isEnded && (currOrder?.endType === 'manual' ? '人工审核' : '系统结算')
              }
            />
          </Steps>
        </div>
      </ProCard>
      {currOrder && currOrder.plateChangeLogs?.length > 0 && (
        <ProCard
          title={
            <>
              <ReconciliationOutlined style={{ color: '#888' }} />
              <span style={{ margin: '0 12px 0 8px' }}>车牌变更记录</span>
            </>
          }
        >
          <ChangeLogList logList={currOrder.plateChangeLogs} />
        </ProCard>
      )}
      {currOrder && currOrder.timeChangeLogs?.length > 0 && (
        <ProCard
          title={
            <>
              <ReconciliationOutlined style={{ color: '#888' }} />
              <span style={{ margin: '0 12px 0 8px' }}>时间变更记录</span>
            </>
          }
        >
          <ChangeTimeList changeList={currOrder.timeChangeLogs} />
        </ProCard>
      )}
      {currOrder && (
        <ProCard
          title={
            <>
              <PayCircleOutlined
                style={{
                  color: '#888',
                }}
              />
              <span style={{ margin: '0 12px 0 8px' }}>支付记录</span>
            </>
          }
          bodyStyle={{
            paddingTop: '5px',
            paddingBottom: '5px',
          }}
        >
          <PaymentRecord
            orderNo={orderNo}
            payStatus={currOrder.payStatus}
            canRefundAmount={getCanRefundAmount(currOrder?.actualAmount, currOrder.refundedAmount)}
            carOut={currOrder?.carOut}
            records={currOrder?.paymentRecords}
            refundRecords={currOrder?.refundRecords || []}
            refresh={() => refreshDetail()}
          />
        </ProCard>
      )}
      {/* <div style={{ width: '100%', textAlign: 'center' }}> */}
      {currOrder?.carOut && !currOrder.canceled && ifModify && currOrder?.actualAmount <= 0 && (
        <CancelOrder
          orderNo={currOrder.orderNo}
          reload={() => {
            refreshDetail();
          }}
        />
      )}
      {/* </div> */}
    </ModalForm>
  );
};
